package com.googlecode.gwtbb.client.only.widget.form.entry;

import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.gwtbb.client.shared.util.StringUtils;
import com.googlecode.gwtbb.client.shared.validation.FieldId;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Apr 30, 2008
 */
public class LabeledCheckGroupFormEntry extends LabeledFormEntry {
	private List<CheckBox> entryCheckGroup;
	private Panel checkBoxesPanel;

	public LabeledCheckGroupFormEntry(FieldId fieldId, String defaultValue, int row, int col, String labelText, List<CheckBox> entryCheckGroup) {
		super(fieldId, defaultValue, row, col, labelText);
		checkBoxesPanel = new FlowPanel();
		setEntryCheckGroup(entryCheckGroup);
		clearValue();
	}

	public Panel getCheckBoxesPanel() {
		return checkBoxesPanel;
	}

	public List<CheckBox> getEntryCheckGroup() {
		return entryCheckGroup;
	}

	public Widget getEntryWidget() {
		return checkBoxesPanel;
	}

	public String getValue() {
		return StringUtils.join(getValues(), ",");
	}

	public List<String> getValues() {
		List<String> retVal = new ArrayList<String>(entryCheckGroup.size());
		for (CheckBox cb : entryCheckGroup)
			if (cb.isChecked())
				retVal.add(cb.getName());
		return retVal;
	}

	public void setEntryCheckGroup(List<CheckBox> entryCheckGroup) {
		this.entryCheckGroup = entryCheckGroup;
		checkBoxesPanel.clear();
		for (CheckBox cb : entryCheckGroup)
			checkBoxesPanel.add(cb);
	}

	public void setValue(String value) {
		if (value == null) {
			for (CheckBox cb : entryCheckGroup)
				cb.setChecked(false);
		} else {
			List<String> values = Arrays.asList(value.split(","));
			for (CheckBox cb : entryCheckGroup)
				cb.setChecked(values.contains(cb.getName()));
		}
	}
}